package com.benyanyi.image_grid_lib;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mylove
 * @date 2021/9/30
 * @email ben@yanyi.red
 * @overview
 */
public class ImageDetailsActivity extends AppCompatActivity {

    private ViewPager2 viewPager;

    private int position = 0;

    private List<String> imgUrls = new ArrayList<>();

    public static void start(Context context, List<String> imgUrls, int position) {
        Intent starter = new Intent(context, ImageDetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("urls", new Gson().toJson(imgUrls));
        bundle.putInt("index", position);
        starter.putExtras(bundle);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.benyanyi_img_details);
        viewPager = findViewById(R.id.view_pager);
        findViewById(R.id.back).setOnClickListener(view -> finish());
        Bundle bundle = getIntent().getExtras();
        String urls = bundle.getString("urls", "");
        position = bundle.getInt("index", 0);
        if (!urls.isEmpty() && !TextUtils.isEmpty(urls)) {
            imgUrls = new Gson().fromJson(urls, new TypeToken<List<String>>() {
            }.getType());
        }
        List<Fragment> fragments = new ArrayList<>();
        for (int i = 0; i < imgUrls.size(); i++) {
            fragments.add(ImageDetailsFragment.newInstance(imgUrls.get(i)));
        }
        ImageDetailsAdapter adapter = new ImageDetailsAdapter(this, fragments);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(position);
    }
}
